#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import glob
import time
import jpype

reload(sys)
sys.setdefaultencoding('utf-8')


class HBaseService(object):
    def __init__(self, jarpath=None, maxtry=4):
        if jarpath is None:
            path = os.path.abspath(__file__)
            jarpath = os.path.join(os.path.dirname(path), 'dsap')

        self.maxtry = maxtry

        jars = ':'.join(glob.glob(os.path.join(jarpath, '*.jar')))
        jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jars)

        self.SCFInit = jpype.JClass("com.bj58.spat.scf.client.SCFInit")
        self.SCFInit.init(os.path.join(jarpath, 'scf.config'))

        self.ProxyFactory = jpype.JClass("com.bj58.spat.scf.client.proxy.builder.ProxyFactory")

        URL = "tcp://dsapapi/HBaseApi"
        self.ihbase = jpype.JClass("com.bj58.dsap.api.scf.contract.IHbaseApi")
        self.hbase = self.ProxyFactory.create(self.ihbase, URL)

    def queryByRowKey(self, table, rowKey):
        try:
            scfmap = self.hbase.queryByRowKey(table, rowKey).getScfMap()
        except Exception, e:  # TimeoutException
            print e
            return {}

        result = {}
        for k in scfmap.keySet():
            result[k] = scfmap[k]
        return result

    def queryMultiByRowKeyList(self, table, rowKeyList):
        jlist = jpype.java.util.ArrayList()
        for rowKey in rowKeyList:
            jlist.add(rowKey)

        result = {}

        nowtry = 0
        while True:
            try:
                listscfmap = self.hbase.queryByRowKey(table, jlist)
                break
            except Exception, e:  # TimeoutException
                nowtry += 1
                if nowtry < self.maxtry:
                    print e
                    time.sleep(2)
                else:
                    return result

        for i in range(listscfmap.size()):
            scfmap = listscfmap.get(i).getScfMap()
            rowkey = scfmap['rowKey']
            if rowkey is None: continue

            result[rowkey] = {}
            for k in scfmap.keySet():
                if k == 'rowKey': continue
                result[rowkey][k] = scfmap[k]

        return result

    # def searchByPrefixFilter(self, table, rowPrefix):
    #     try:
    #         listscfmap = self.hbase.searchByPrefixFilter(table, rowPrefix)
    #     except Exception, e:  # TimeoutException
    #         print e
    #         return []
    #     return listscfmap

    def nextPagesByKeyPrefix(self, table, prefix, callback, *args):
        offsetKey = ''
        pageSize = 1000
        nowtry = 0

        while True:
            try:
                listscfmap = self.hbase.nextPagesByKeyPrefix(table, prefix, offsetKey, pageSize)
                if listscfmap.size() == 0:
                    return True

                callback(listscfmap, *args)

                offsetKey = listscfmap.get(listscfmap.size() - 1).getScfMap()['rowKey']
                nowtry = 0
            except Exception, e:
                print e
                if nowtry < self.maxtry:
                    nowtry += 1
                    time.sleep(2)
                else:
                    return False

    def shutdown(self):
        jpype.shutdownJVM()



